'''
Created on 26 mai 2011

@author: rdionisi
'''


from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import Context, loader
from django.views.generic.simple import direct_to_template
from filetransfers.api import prepare_upload, prepare_upload, serve_file
from google.appengine.ext import blobstore, webapp
from google.appengine.ext.webapp import blobstore_handlers, template
from google.appengine.ext.webapp.util import run_wsgi_app
from wikiproduct.forms import UploadForm
from wikiproduct.models import Product, UploadModel
import urllib


def index(request):
    latest_product_list = Product.objects.all()[:5]
    #t = loader.get_template('products/index.html')
    #c = Context({
    #    'latest_product_list': latest_product_list,
    #})
    #return HttpResponse(t.render(c))
    return render_to_response('products/index.html', {'latest_product_list': latest_product_list})


def detail(request, product_id):
    p = get_object_or_404(Product, pk=product_id)
    #try:
    #    p = Product.objects.get(pk=product_id)
    #except Product.DoesNotExist:
    #    raise Http404
    return render_to_response('products/detail.html', {'product': p})

def upload_handler(request):
    view_url = reverse('wikiproduct.views.upload_handler')
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect(view_url)

    upload_url, upload_data = prepare_upload(request, view_url)
    form = UploadForm()
    return direct_to_template(request, 'blobstore.html',
        {'form': form, 'upload_url': upload_url, 'upload_data': upload_data,
         'uploads': UploadModel.objects.all()})    
    
def download_handler(request, pk):
    upload = get_object_or_404(UploadModel, pk=pk)
    return serve_file(request, upload.file, save_as=True)

def delete_handler(request, pk):
    if request.method == 'POST':
        upload = get_object_or_404(UploadModel, pk=pk)
        upload.file.delete()
        upload.delete()
    return HttpResponseRedirect(reverse('wikiproduct.views.upload_handler'))
